package com.blog.cloud.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * 网关服务跨域配置
 *
 * @author 龙茶清欢
 * @since 2022-10-08 00:13:17
 */
@Configuration
public class CorsConfig {

    /**
     * 该配置适用于reactive响应式环境
     * @return CorsWebFilter
     */
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        // springboot升级成2.4.0以上时对AllowedOrigin设置发生了改变，不能有”*“,可以替换成AllowedOriginPattern
        config.addAllowedOriginPattern("*");
//        config.addAllowedOrigin("*");
        config.setAllowCredentials(true);

        // 必须是reactive包下的UrlBasedCorsConfigurationSource
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}

// 从springboot 2.7 开始spring.factory自动配置的方式将被弃用，取而代之的是
// /META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 自动配置文件中配置对应的全限定类名，例如：com.spring4all.swagger.SwaggerAutoConfiguration
// 具体参考 https://cloud.tencent.com/developer/article/2010301